/**
 * 卖家店铺笔记类
 * @type {*|exports|module.exports}
 */
var AV = require('leanengine');
// 状态  0代表flase，1代表true
var rState="";	
var rCode="";
// 如有错误或异常，该列才有值/
var rMsg="";
// 通用返回对象
var rResult = "";
var err;
var common   = require( '../cloud/common' );
var shopYySellerGoods = require( '../cloud/shopYySellerGoods' );
var apis = require( '../cloud/lib/apis' );
/**
 * 添加店长笔记
 * @param request
 * @param response
 */
function addNote(request, callback){
	var uId=request.user.id;
	var pics=request.params.pics;
	var title=request.params.title;
	var content=request.params.content;
	if(title==null||title==undefined){
		title="";
	}
	if(content==null||content==undefined){
		content="";
	}
	title=title.replace(/\s/g, "");//去空格
	content=content.replace(/\s/g, "");//去空格
	//对pics进行去重
	if(pics!=undefined&&pics[0]!=undefined&&pics[0]!=""){
		pics=common.arrayDistinctStr(pics);
	}else{
		pics=[];
	}	
	var Shop_seller_note =common.getEntity("Shop_seller_note");
	var sellerNote= new Shop_seller_note();
	//查询是否拥有店铺
	shopYySellerGoods.findShopByUserOId(uId,function(shopObj){
		if(shopObj==null){
			return callback(null,JSON.stringify(common.getErrArr("请先创建一个店铺")));
		}else{
			if(shopObj.get("status")=="0"){
				return callback(null,JSON.stringify(common.getErrArr("您的店铺已被关闭")));
			}else{
				sellerNote.set("title",title);
				sellerNote.set("content",content);
				sellerNote.set("shopOId",shopObj.id);
				sellerNote.set("status","1");
				sellerNote.set("userOId",request.user.id);
				if(pics[0]["objectId"]!=undefined&&pics[0]["objectId"]!=null)
					sellerNote.set("picName",pics[0]["objectId"]);
				sellerNote.set("shopObj",{"__type":"Pointer",className:"Shop_shop",objectId:shopObj.id});
				sellerNote.set("userObj",{"__type":"Pointer",className:"_User",objectId:uId});
				sellerNote.save(null, {
					success : function(sellerNote) {
						//保存笔记图片
						saveNotePics(sellerNote,pics,function(err,count){
							if(err){
								return callback(null,JSON.stringify(common.getErrArr(err)));
							}else{
								var result={};
								result["noteOId"]=sellerNote.id;
								var returnArr=common.getReturnArr("1","1000","",result);
								return callback(null,JSON.stringify(returnArr)); 
							}
						});
					},
					error : function(errObj,error) {
					return callback(null,JSON.stringify(common.getErrArr(error)));
					}
				});
			}			
		}
	});
}
/**
 * 查看笔记列表
 * @param request
 * @param callback
 */
function noteList(request, callback){
	var page=request.params.page;
	if(page==""||page==null||page==undefined){
		page=1;
	}else{
		page=parseInt(page);
	}
	if(isNaN(page))
		page=1;
	var num=10;
	//查询是否拥有店铺
	shopYySellerGoods.findShopByUserOId(request.user.id,function(shopObj){
		if(shopObj==null){
			return callback(null,JSON.stringify(common.getErrArr("请先创建一个店铺")));
		}else{
			if(shopObj.get("status")=="0"){
				return callback(null,JSON.stringify(common.getErrArr("您的店铺已被关闭")));
			}else{
				noteListCommon(shopObj.id,page,num,function(err,returnStr){
					return callback(err,returnStr);
				})
			}
		}
	});
}
function noteListCommon(shopOId,page,num,callback){
	if(shopOId==""||shopOId==null||shopOId==undefined){
		return callback(null,JSON.stringify(common.getErrArr("错误的参数")));
	}
	var query = new AV.Query('Shop_seller_note');
	query.equalTo("shopOId",shopOId);
	query.equalTo("status","1");
	query.skip((page-1)*num);
	query.limit(num);
	query.descending("updatedAt");
	query.find({
		success : function(sellerNoteObj) {
			var noteInfo=[];
			var noteOIds= [];
			var noteObj=null;
			var pics=null;
			var picObj=null;
			for(var i=0;i<sellerNoteObj.length;i++){
				noteOIds.push(sellerNoteObj[i].id);
				noteObj=common.getSellerNote(sellerNoteObj[i]);
				pics=[];
				if(noteObj["picName"]!=""){
					picObj={};
					picObj["objectId"]="";
					picObj["picURL"]=apis['qiniu']['url'] + "/"+noteObj["picName"];
					picObj["picWidthxHeight"]="1x1";
					picObj["sortNum"]=1;
					pics.push(picObj);
				}
				noteObj["pic"]=pics;
				noteInfo.push(noteObj);
			}
			var returnArr=common.getReturnArr("1","1000","",noteInfo);
			returnArr["currentPage"]=page;
			return callback(null,JSON.stringify(returnArr)); 								
		},
        error: function(errObj,error) {	        	
			return callback(null,JSON.stringify(common.getErrArr(error)));
	  }
	});
}
/**
 * 买家查看卖家笔记
 * @param request
 * @param callback
 */
function sellerNoteList(request, callback){
	var shopOId=request.params.shopOId;
	var page=request.params.page;
	if(page==""||page==null||page==undefined){
		page=1;
	}else{
		page=parseInt(page);
	}
	if(isNaN(page))
		page=1;
	var num=10;
	noteListCommon(shopOId,page,num,function(err,returnStr){
		return callback(err,returnStr);
	})
}
/**
 * 删除店长笔记
 * @param request
 * @param callback
 */
function delNote(request, callback){
	var noteOId=request.params.noteOId;
	if(noteOId==""||noteOId==null||noteOId==undefined){
		return callback(null,JSON.stringify(common.getErrArr("错误的参数")));
	}
	var query = new AV.Query('Shop_seller_note');
	query.equalTo("objectId",noteOId);
	query.equalTo("status","1");
	query.equalTo("userOId",request.user.id);
	query.first({
		success : function(sellerNoteObj) {
			if(sellerNoteObj!=null){
				sellerNoteObj.set("status","-1");
				sellerNoteObj.save(null,{
					success: function(sellerNoteObj) {
						var returnArr=common.getReturnArr("1","1000","","");
						return callback(null,JSON.stringify(returnArr)); 
					},
				    error: function(errObj,error) {	        	
				    	return callback(null,JSON.stringify(common.getErrArr(error)));
					}
				});
			}else{
				return callback(null,JSON.stringify(common.getErrArr("无效的信息，请刷新后重试")));
			}
		},
        error: function(error) {	        	
        	return callback(null,JSON.stringify(common.getErrArr(error)));
	  }
	});
}
/**
 * 前往编辑和笔记详情（卖家版）
 * @param request
 * @param callback
 */
function goEditNote(request, callback){
	var noteOId=request.params.noteOId;
	if(noteOId==""||noteOId==null||noteOId==undefined){
		return callback(null,JSON.stringify(common.getErrArr("错误的参数")));
	}
	//查询是否拥有店铺
	shopYySellerGoods.findShopByUserOId(request.user.id,function(shopObj){
		if(shopObj==null){
			return callback(null,JSON.stringify(common.getErrArr("请先创建一个店铺")));
		}else{
			if(shopObj.get("status")=="0"){
				return callback(null,JSON.stringify(common.getErrArr("您的店铺已被关闭")));
			}else{
				var query = new AV.Query('Shop_seller_note');
				query.equalTo("objectId",noteOId);
				query.equalTo("status","1");
				query.equalTo("userOId",request.user.id);
				query.first({
					success : function(sellerNoteObj) {
						if(sellerNoteObj!=null){
							var noteObj=common.getSellerNote(sellerNoteObj);
							var noteId=[];
							noteId.push(noteOId);
							getNotePicInfo(noteId,function(notePicInfo){
								 if(notePicInfo[noteOId]!=null&&notePicInfo[noteOId]!=undefined&&notePicInfo[noteOId]!=""){
									 noteObj["pic"]=notePicInfo[noteOId];
								 }else{
									 noteObj["pic"]=[];
								 }
								 noteObj["shopName"]=shopObj.get("name");
								if (shopObj.get("icon") != null && shopObj.get("icon") != ""&&shopObj.get("icon") !=undefined) {
									noteObj["icon"] = shopObj.get("icon")._url;
									noteObj["iconId"] = shopObj.get("icon").id;
								} else {
									noteObj["icon"] = "";
									noteObj["iconId"] = "";
								}
								var returnArr=common.getReturnArr("1","1000","",noteObj);
								return callback(null,JSON.stringify(returnArr)); 
						   });
						}else{
							return callback(null,JSON.stringify(common.getErrArr("无效的信息，请刷新后重试")));
						}
					},
			        error: function(error) {	        	
						return callback(null,JSON.stringify(common.getErrArr(error)));
				  }
				});
			}
		}
	});
}
/**
 * 店长笔记详情
 * @param request
 * @param callback
 */
function noteInfo(request, callback){
	var noteOId=request.params.noteOId;
	if(noteOId==""||noteOId==null||noteOId==undefined){
		return callback(null,JSON.stringify(common.getErrArr("错误的参数")));
	}
	var query = new AV.Query('Shop_seller_note');
	query.equalTo("objectId",noteOId);
	query.equalTo("status","1");
	query.include("shopObj");
	query.first({
		success : function(sellerNoteObj) {
			if(sellerNoteObj!=null){
				var noteObj=common.getSellerNote(sellerNoteObj);
				var noteId=[];
				noteId.push(noteOId);
				getNotePicInfo(noteId,function(notePicInfo){
					if(notePicInfo[noteOId]!=null&&notePicInfo[noteOId]!=undefined&&notePicInfo[noteOId]!=""){
						 noteObj["pic"]=notePicInfo[noteOId];
					}else{
						 noteObj["pic"]=[];
					}
					var shopObj=sellerNoteObj.get("shopObj");
					noteObj["shopOId"]="";
					noteObj["shopName"]="";
					noteObj["icon"] = "";
					noteObj["iconId"] = "";
					if(shopObj!=""&&shopObj!=null&&shopObj!=undefined){
						noteObj["shopName"]=shopObj.get("name");
						noteObj["shopOId"]=shopObj.id;
						if (shopObj.get("icon") != null && shopObj.get("icon") != ""&&shopObj.get("icon") !=undefined) {
							noteObj["icon"] = shopObj.get("icon")._url;
							noteObj["iconId"] = shopObj.get("icon").id;
						}
					}
					var returnArr=common.getReturnArr("1","1000","",noteObj);
					return callback(null,JSON.stringify(returnArr)); 
				});				
			}else{
				return callback(null,JSON.stringify(common.getErrArr("无效的信息，请刷新后重试")));
			}
		},
        error: function(error) {	        	
			return callback(null,JSON.stringify(common.getErrArr(error)));
	  }
	});
}
/**
 * 编辑店长笔记
 * @param request
 * @param callback
 */
function updateNote(request, callback){
	var noteOId=request.params.noteOId;
	var title=request.params.title;
	var content=request.params.content;
	if(title==null||title==undefined){
		title="";
	}
	if(content==null||content==undefined){
		content="";
	}
	title=title.replace(/\s/g, "");//去空格
	content=content.replace(/\s/g, "");//去空格
	var pics=request.params.pics;
	//对pics进行去重
	if(pics!=undefined&&pics[0]!=undefined&&pics[0]!=""){
		pics=common.arrayDistinctStr(pics);
	}else{
		pics=[];
	}
	//查询是否拥有店铺
	shopYySellerGoods.findShopByUserOId(request.user.id,function(shopObj){
		if(shopObj==null){
			return callback(null,JSON.stringify(common.getErrArr("请先创建一个店铺")));
		}else{
			if(shopObj.get("status")=="0"){
				return callback(null,JSON.stringify(common.getErrArr("您的店铺已被关闭")));
			}else{
				var query = new AV.Query('Shop_seller_note');
				query.equalTo("objectId",noteOId);
				query.equalTo("status","1");
				query.equalTo("userOId",request.user.id);
				query.first({
					success : function(sellerNoteObj) {
						if(sellerNoteObj!=null){
							if(title!=null||title!=""){
								sellerNoteObj.set("title",title);
							}
							if(content!=null||content!=""){
								sellerNoteObj.set("content",content);
							}
							sellerNoteObj.set("picName",pics[0]["objectId"]);
							sellerNoteObj.save(null,{
								 success: function(sellerNoteObj) {
									 //删除笔记样式图
									 delNotePics(noteOId,function(state){
											if(state==1){
												//保存笔记图片
												saveNotePics(sellerNoteObj,pics,function(err,count){
													if(err){
														return callback(null,JSON.stringify(common.getErrArr(err)));
													}else{
														var result={};
														result["noteOId"]=noteOId;
														var returnArr=common.getReturnArr("1","1000","",result);
														return callback(null,JSON.stringify(returnArr)); 
													}
												});
											}
										});																					 							 									
								 },
							      error: function(errObj,error) {	        	
										return callback(null,JSON.stringify(common.getErrArr(error)));
								  }
							});
						}else{
							return callback(null,JSON.stringify(common.getErrArr("无效的信息，请稍后重试")));
						}
		
					},
			        error: function(error) {	        	
						return callback(null,JSON.stringify(common.getErrArr(error)));
				  }
				});
			}
   }
});
}
/**
 * 保存笔记样式图
 * @param noteOId 笔记标识符
 * @param pics 样式图数组
 * @param callback
 */
function saveNotePics(noteObj,pics,callback){
	if(pics==undefined||pics[0]==undefined||pics[0]==""){
		return callback(null,0);
	}
	var notePicsArry=[];
	var picIds=[];
	for ( var i = 0; i < pics.length; i++) {
		picIds.push(pics[i]["objectId"]);
	}
	//查询图片对象数组
	var ShopNotePic = common.getEntity("Shop_notePic");
	for ( var i = 0; i < picIds.length; i++) {
			var shopNotePic = new ShopNotePic();
			shopNotePic.set("noteOId", noteObj.id);
			shopNotePic.set("picName", picIds[i]);
			shopNotePic.set("sortNum",i+1);
			notePicsArry.push(shopNotePic);
	}
	 AV.Object.saveAll(notePicsArry, function(list, error) {
		 var count=0;
		 if(list){
			 noteObj.set("picArray",notePicsArry);
			 noteObj.save();
			 count=list.length;
		 }
		 return callback(error,count);
	});
}

exports.getNotePicInfo = getNotePicInfo;
/**
 * 得到店长笔记图片
 * @param noteOIds
 * @param callback
 */
function getNotePicInfo(noteOIds,callback){
	if(noteOIds==""||noteOIds==null||noteOIds==undefined){
		return callback(null);
	}
	var query = new AV.Query('Shop_notePic');
	query.containedIn("noteOId", noteOIds);
	query.ascending("sortNum");
	query.find({
		success : function(notePicsObj) {
			var notePicInfo={};
			for(var i=0;i< noteOIds.length;i++ ){
				var picObj=[];
				for(var j = 0; j < notePicsObj.length; j++){
					if(noteOIds[i]==notePicsObj[j].get("noteOId")){
					   picObj.push(common.getNotePic(notePicsObj[j]));
					}
			   }
			notePicInfo[noteOIds[i]]=picObj;
			}		
			return callback(notePicInfo);
		},
		error: function(err){
			return callback(null);
		}
	});
}
/**
 * 删除店长笔记样式图
 * @param goodObj
 * @param callback
 */
function delNotePics(noteOId,callback){
	if(noteOId==""||noteOId==null||noteOId==undefined){
		return callback(0);
	}
	var query = new AV.Query('Shop_notePic');
	query.equalTo("noteOId", noteOId);
	query.destroyAll({
		success: function(obj){
		  return callback(1);
		},
		error: function(err){
		   return callback(0);
		}
	});
}
/**
 * 初始化笔记图片
 * @param noteOId
 * @param callback
 */
function initNotePics(noteOId,callback){
	var query = new AV.Query('Shop_seller_note');
	var page=1;
	query.limit(999);
	query.find({
		  success: function(obj){
			  var noteOIdArr= [];
			     for(i=0;i<obj.length;i++){
			    	 noteOIdArr[i]=obj[i].id;
			     }
			     var queryPic = new AV.Query('Shop_notePic');
			     queryPic.containedIn("noteOId", noteOIdArr);
			     queryPic.ascending("sortNum");
			     queryPic.skip((page-1)*800);
			     queryPic.limit(999);
			     queryPic.find({
						success : function(notePicsObj) {
							//var notePicInfo={};
							for(var i=0;i< obj.length;i++ ){
								
								var picObj=[];
								
								for(var j = 0; j < notePicsObj.length; j++){
									var notePicInfoObj={};
									if(obj[i].id==notePicsObj[j].get("noteOId")){

										var picArr={"__type":"Pointer",className:"Shop_notePic",objectId:notePicsObj[j].id}	
										 picObj.push(picArr);
									}
							   }
								obj[i].set("picArray",picObj);								
								obj[i].save()
								//notePicInfo[noteOIds[i]]=picObj;
							}		
							var returnArr=common.getReturnArr("1","1000","","OK");
							return callback(null,JSON.stringify(returnArr)); 
						},
						   error: function(err){
							   return callback(null);
						   }
					});
									     
			   },
			   error: function(err){
				   return callback(0);
			   }
	});
	
	
}
/*
 *初始化笔记图片
 */
AV.Cloud.define("initNotePics",function(request, response) {
	   if(!common.verifyLogin(request, response)){
		return response.error("登陆信息过期，请尝试重新登陆。");		
	   }else{
		   
		   initNotePics(request, function(error,returnStr) {
			if(error){
				return response.error(returnStr);
			}else{
				return response.success(returnStr);
			}
		   });
	   }
});
			


/*
 *添加店长笔记
 */
AV.Cloud.define("addNote",function(request, response) {
	   if(!common.verifyLogin(request, response)){
		return response.error("登陆信息过期，请尝试重新登陆。");		
	   }else{
		   var params={};
			//params["商品图片不能为空"]=request.params.pics;
			params["笔记标题不能为空"]=request.params.title;			
			params["系统分类不能为空"]=request.params.content;
			var msg=common.validateParamsEmpty(params);
			if(msg!=null){
				return response.success(JSON.stringify(common.getErrArr(msg)));
			}else{
				addNote(request, function(error,returnStr) {
					if(error){
						return response.error(returnStr);
					}else{
						return response.success(returnStr);
					}
				});
			}
		   		    
		}
});
/*
 *店长笔记列表
 */
AV.Cloud.define("noteList",function(request, response) {
	   if(!common.verifyLogin(request, response)){
		return response.error("登陆信息过期，请尝试重新登陆。");		
	   }else{		   
		   noteList(request, function(error,returnStr) {
				if(error){
					return response.error(returnStr);
				}else{
					return response.success(returnStr);
				}
			});
			
		   		    
		}
});
/*
 * 删除店长笔记
 */
AV.Cloud.define("delNote",function(request, response) {
	   if(!common.verifyLogin(request, response)){
		return response.error("登陆信息过期，请尝试重新登陆。");		
	   }else{
		   if(request.params.noteOId==""||request.params.noteOId==null){
			   return response.success(JSON.stringify(common.getErrArr("请传入正确的参数！")));
		   }else{
			   delNote(request, function(error,returnStr) {
					if(error){
						return response.error(returnStr);
					}else{
						return response.success(returnStr);
					}
				});
		   }
		}
});
/*
 * 编辑店长笔记
 */
AV.Cloud.define("updateNote",function(request, response) {
	   if(!common.verifyLogin(request, response)){
		return response.error("登陆信息过期，请尝试重新登陆。");		
	   }else{
		   if(request.params.noteOId==""||request.params.noteOId==null){
			   return response.success(JSON.stringify(common.getErrArr("请传入正确的参数！")));
		   }else{
			   updateNote(request, function(error,returnStr) {
					if(error){
						return response.error(returnStr);
					}else{
						return response.success(returnStr);
					}
				});
		   }
		}
});
/*
 *买家查看卖家笔记
 */
AV.Cloud.define("sellerNoteList",function(request, response) {
	   if(!common.verifyLogin(request, response)){
		return response.error("登陆信息过期，请尝试重新登陆。");		
	   }else{	
		   if(request.params.shopOId==""||request.params.shopOId==null){
			   return response.success(JSON.stringify(common.getErrArr("请传入正确的参数！")));
		   }else{
			   sellerNoteList(request, function(error,returnStr) {
					if(error){
						return response.error(returnStr);
					}else{
						return response.success(returnStr);
					}
				});  
		   }
		}
});
/*
 *前往编辑和笔记详情（卖家版）
 */
AV.Cloud.define("goEditNote",function(request, response) {
	   if(!common.verifyLogin(request, response)){
		return response.error("登陆信息过期，请尝试重新登陆。");		
	   }else{	
		   if(request.params.noteOId==""||request.params.noteOId==null){
			   return response.success(JSON.stringify(common.getErrArr("请传入正确的参数！")));
		   }else{
			   goEditNote(request, function(error,returnStr) {
					if(error){
						return response.error(returnStr);
					}else{
						return response.success(returnStr);
					}
				});  
		   }
		}
});
/*
 *笔记详情（买家版）
 */
AV.Cloud.define("noteInfo",function(request, response) {
	   if(!common.verifyLogin(request, response)){
		return response.error("登陆信息过期，请尝试重新登陆。");		
	   }else{	
		   if(request.params.noteOId==""||request.params.noteOId==null){
			   return response.success(JSON.stringify(common.getErrArr("请传入正确的参数！")));
		   }else{
			   noteInfo(request, function(error,returnStr) {
					if(error){
						return response.error(returnStr);
					}else{
						return response.success(returnStr);
					}
				});  
		   }
		}
});